package UML_ER.diagram.edit.parts;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

import org.eclipse.draw2d.GridData;
import org.eclipse.draw2d.GridLayout;
import org.eclipse.draw2d.IFigure;
import org.eclipse.draw2d.MarginBorder;
import org.eclipse.draw2d.PositionConstants;
import org.eclipse.draw2d.RectangleFigure;
import org.eclipse.draw2d.RoundedRectangle;
import org.eclipse.draw2d.Shape;
import org.eclipse.draw2d.StackLayout;
import org.eclipse.draw2d.ToolbarLayout;
import org.eclipse.draw2d.geometry.Dimension;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.gef.EditPart;
import org.eclipse.gef.EditPolicy;
import org.eclipse.gef.GraphicalEditPart;
import org.eclipse.gef.Request;
import org.eclipse.gef.commands.Command;
import org.eclipse.gef.editpolicies.LayoutEditPolicy;
import org.eclipse.gef.editpolicies.NonResizableEditPolicy;
import org.eclipse.gef.handles.MoveHandle;
import org.eclipse.gef.requests.CreateRequest;
import org.eclipse.gmf.runtime.diagram.core.edithelpers.CreateElementRequestAdapter;
import org.eclipse.gmf.runtime.diagram.ui.editparts.AbstractBorderedShapeEditPart;
import org.eclipse.gmf.runtime.diagram.ui.editparts.IBorderItemEditPart;
import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart;
import org.eclipse.gmf.runtime.diagram.ui.editparts.ShapeNodeEditPart;
import org.eclipse.gmf.runtime.diagram.ui.editpolicies.BorderItemSelectionEditPolicy;
import org.eclipse.gmf.runtime.diagram.ui.editpolicies.CreationEditPolicy;
import org.eclipse.gmf.runtime.diagram.ui.editpolicies.DragDropEditPolicy;
import org.eclipse.gmf.runtime.diagram.ui.editpolicies.EditPolicyRoles;
import org.eclipse.gmf.runtime.diagram.ui.figures.BorderItemLocator;
import org.eclipse.gmf.runtime.diagram.ui.requests.CreateViewAndElementRequest;
import org.eclipse.gmf.runtime.draw2d.ui.figures.ConstrainedToolbarLayout;
import org.eclipse.gmf.runtime.draw2d.ui.figures.WrappingLabel;
import org.eclipse.gmf.runtime.emf.type.core.IElementType;
import org.eclipse.gmf.runtime.gef.ui.figures.DefaultSizeNodeFigure;
import org.eclipse.gmf.runtime.gef.ui.figures.NodeFigure;
import org.eclipse.gmf.runtime.notation.LineType;
import org.eclipse.gmf.runtime.notation.Node;
import org.eclipse.gmf.runtime.notation.View;
import org.eclipse.gmf.tooling.runtime.edit.policies.reparent.CreationEditPolicyWithCustomReparent;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.widgets.Display;

import UML_ER.Entity;
import UML_ER.diagram.edit.policies.EntityItemSemanticEditPolicy;
import UML_ER.diagram.part.UML_ERVisualIDRegistry;
import UML_ER.diagram.providers.UML_ERElementTypes;

/**
 * @generated
 */
public class EntityEditPart extends ShapeNodeEditPart {

	/**
	 * @generated
	 */
	public static final int VISUAL_ID = 2003;

	/**
	 * @generated
	 */
	protected IFigure contentPane;

	/**
	 * @generated
	 */
	protected IFigure primaryShape;

	/**
	 * @generated
	 */
	public EntityEditPart(View view) {
		super(view);
	}

	/**
	 * @generated
	 */
	protected void createDefaultEditPolicies() {
		installEditPolicy(EditPolicyRoles.CREATION_ROLE,
				new CreationEditPolicyWithCustomReparent(
						UML_ERVisualIDRegistry.TYPED_INSTANCE));
		super.createDefaultEditPolicies();
		installEditPolicy(EditPolicyRoles.SEMANTIC_ROLE,
				new EntityItemSemanticEditPolicy());
		installEditPolicy(EditPolicy.LAYOUT_ROLE, createLayoutEditPolicy());
		// XXX need an SCR to runtime to have another abstract superclass that would let children add reasonable editpolicies
		// removeEditPolicy(org.eclipse.gmf.runtime.diagram.ui.editpolicies.EditPolicyRoles.CONNECTION_HANDLES_ROLE);
	}

	/**
	 * @generated
	 */
	protected LayoutEditPolicy createLayoutEditPolicy() {
		org.eclipse.gmf.runtime.diagram.ui.editpolicies.LayoutEditPolicy lep = new org.eclipse.gmf.runtime.diagram.ui.editpolicies.LayoutEditPolicy() {

			protected EditPolicy createChildEditPolicy(EditPart child) {
				EditPolicy result = child
						.getEditPolicy(EditPolicy.PRIMARY_DRAG_ROLE);
				if (result == null) {
					result = new NonResizableEditPolicy();
				}
				return result;
			}

			protected Command getMoveChildrenCommand(Request request) {
				return null;
			}

			protected Command getCreateCommand(CreateRequest request) {
				return null;
			}
		};
		return lep;
	}

	/**
	 * @generated
	 */
	protected IFigure createNodeShape() {
		return primaryShape = new EntityFigure();
	}

	/**
	 * @generated
	 */
	public EntityFigure getPrimaryShape() {
		return (EntityFigure) primaryShape;
	}

	/**
	 * @generated
	 */
	protected boolean addFixedChild(EditPart childEditPart) {
		if (childEditPart instanceof EntityNameEditPart) {
			((EntityNameEditPart) childEditPart).setLabel(getPrimaryShape()
					.getEntityFigureName());
			return true;
		}
		return false;
	}

	/**
	 * @generated
	 */
	protected boolean removeFixedChild(EditPart childEditPart) {
		if (childEditPart instanceof EntityNameEditPart) {
			return true;
		}
		return false;
	}

	/**
	 * @generated
	 */
	protected void addChildVisual(EditPart childEditPart, int index) {
		if (addFixedChild(childEditPart)) {
			return;
		}
		super.addChildVisual(childEditPart, -1);
	}

	/**
	 * @generated
	 */
	protected void removeChildVisual(EditPart childEditPart) {
		if (removeFixedChild(childEditPart)) {
			return;
		}
		super.removeChildVisual(childEditPart);
	}

	/**
	 * @generated
	 */
	protected IFigure getContentPaneFor(IGraphicalEditPart editPart) {
		return getContentPane();
	}

	/**
	 * @generated
	 */
	protected NodeFigure createNodePlate() {
		DefaultSizeNodeFigure result = new DefaultSizeNodeFigure(40, 40);
		return result;
	}

	/**
	 * Creates figure for this edit part.
	 * 
	 * Body of this method does not depend on settings in generation model
	 * so you may safely remove <i>generated</i> tag and modify it.
	 * 
	 * @generated
	 */
	protected NodeFigure createNodeFigure() {
		NodeFigure figure = createNodePlate();
		figure.setLayoutManager(new StackLayout());
		IFigure shape = createNodeShape();
		figure.add(shape);
		contentPane = setupContentPane(shape);
		return figure;
	}

	/**
	 * Default implementation treats passed figure as content pane.
	 * Respects layout one may have set for generated figure.
	 * @param nodeShape instance of generated figure class
	 * @generated
	 */
	protected IFigure setupContentPane(IFigure nodeShape) {
		if (nodeShape.getLayoutManager() == null) {
			ConstrainedToolbarLayout layout = new ConstrainedToolbarLayout();
			layout.setSpacing(5);
			nodeShape.setLayoutManager(layout);
		}
		return nodeShape; // use nodeShape itself as contentPane
	}

	/**
	 * @generated
	 */
	public IFigure getContentPane() {
		if (contentPane != null) {
			return contentPane;
		}
		return super.getContentPane();
	}

	/**
	 * @generated
	 */
	protected void setForegroundColor(Color color) {
		if (primaryShape != null) {
			primaryShape.setForegroundColor(color);
		}
	}

	/**
	 * @generated
	 */
	protected void setBackgroundColor(Color color) {
		if (primaryShape != null) {
			primaryShape.setBackgroundColor(color);
		}
	}

	/**
	 * @generated
	 */
	protected void setLineWidth(int width) {
		if (primaryShape instanceof Shape) {
			((Shape) primaryShape).setLineWidth(width);
		}
	}

	/**
	 * @generated
	 */
	protected void setLineType(int style) {
		if (primaryShape instanceof Shape) {
			((Shape) primaryShape).setLineStyle(style);
		}
	}

	/**
	 * @generated
	 */
	public EditPart getPrimaryChildEditPart() {
		return getChildBySemanticHint(UML_ERVisualIDRegistry
				.getType(EntityNameEditPart.VISUAL_ID));
	}

	/**
	 * @generated
	 */
	public List<IElementType> getMARelTypesOnSource() {
		ArrayList<IElementType> types = new ArrayList<IElementType>(1);
		types.add(UML_ERElementTypes.Generalization_4011);
		return types;
	}

	/**
	 * @generated
	 */
	public List<IElementType> getMARelTypesOnSourceAndTarget(
			IGraphicalEditPart targetEditPart) {
		LinkedList<IElementType> types = new LinkedList<IElementType>();
		if (targetEditPart instanceof UML_ER.diagram.edit.parts.EntityEditPart) {
			types.add(UML_ERElementTypes.Generalization_4011);
		}
		return types;
	}

	/**
	 * @generated
	 */
	public List<IElementType> getMATypesForTarget(IElementType relationshipType) {
		LinkedList<IElementType> types = new LinkedList<IElementType>();
		if (relationshipType == UML_ERElementTypes.Generalization_4011) {
			types.add(UML_ERElementTypes.Entity_2003);
		}
		return types;
	}

	/**
	 * @generated
	 */
	public List<IElementType> getMARelTypesOnTarget() {
		ArrayList<IElementType> types = new ArrayList<IElementType>(2);
		types.add(UML_ERElementTypes.Generalization_4011);
		types.add(UML_ERElementTypes.Role_4024);
		return types;
	}

	/**
	 * @generated
	 */
	public List<IElementType> getMATypesForSource(IElementType relationshipType) {
		LinkedList<IElementType> types = new LinkedList<IElementType>();
		if (relationshipType == UML_ERElementTypes.Generalization_4011) {
			types.add(UML_ERElementTypes.Entity_2003);
		} else if (relationshipType == UML_ERElementTypes.Role_4024) {
			types.add(UML_ERElementTypes.BinaryRelationship_2008);
			types.add(UML_ERElementTypes.Relationship_2009);
		}
		return types;
	}

	/**
	 * @generated
	 */
	public EditPart getTargetEditPart(Request request) {
		if (request instanceof CreateViewAndElementRequest) {
			CreateElementRequestAdapter adapter = ((CreateViewAndElementRequest) request)
					.getViewAndElementDescriptor()
					.getCreateElementRequestAdapter();
			IElementType type = (IElementType) adapter
					.getAdapter(IElementType.class);
			if (type == UML_ERElementTypes.Attribute_3001) {
				return getChildBySemanticHint(UML_ERVisualIDRegistry
						.getType(EntityAttributesEditPart.VISUAL_ID));
			}
			if (type == UML_ERElementTypes.OntologyReference_3002) {
				return getChildBySemanticHint(UML_ERVisualIDRegistry
						.getType(EntityAttributes2EditPart.VISUAL_ID));
			}
		}
		return super.getTargetEditPart(request);
	}

	@Override
	protected void handleNotificationEvent(Notification notification) {
		if (notification.getNotifier() instanceof Entity) {
			getPrimaryShape().updateLine();
		}
		super.handleNotificationEvent(notification);
	}

	/**
	 * @generated
	 */
	public class EntityFigure extends RoundedRectangle {

		/**
		 * @generated
		 */
		private WrappingLabel fEntityFigureName;
		/**
		 * @generated
		 */
		private WrappingLabel fEntityFigureStereotype;

		/**
		 * @generated
		 */
		private WrappingLabel fEntityAttribute;
		private int lineWidth = 2;

		/**
		 * @generated
		 */
		public EntityFigure() {
			this.setCornerDimensions(new Dimension(getMapMode().DPtoLP(8),
					getMapMode().DPtoLP(8)));
			this.setLineWidth(2);

			this.setBorder(new MarginBorder(getMapMode().DPtoLP(0),
					getMapMode().DPtoLP(0), getMapMode().DPtoLP(5),
					getMapMode().DPtoLP(0)));
			createContents();
		}

		public void updateLine() {
			Entity entity = (Entity) ((Node) EntityEditPart.this.getModel())
					.getElement();

			lineWidth = 2;
			if (entity.isIsWeak()) {
				lineWidth = 1;
			}
			//this.setLineStyle(LineStyle)
			this.setLineWidth(lineWidth);
		}

		/**
		 * @generated
		 */
		private void createContents() {

			RoundedRectangle entityFIgureName0 = new RoundedRectangle();

			entityFIgureName0.setCornerDimensions(new Dimension(getMapMode()
					.DPtoLP(8), getMapMode().DPtoLP(8)));
			entityFIgureName0.setFill(false);
			entityFIgureName0.setOutline(false);

			this.add(entityFIgureName0);

			ToolbarLayout layoutEntityFIgureName0 = new ToolbarLayout();
			layoutEntityFIgureName0.setStretchMinorAxis(true);
			layoutEntityFIgureName0
					.setMinorAlignment(ToolbarLayout.ALIGN_CENTER);

			layoutEntityFIgureName0.setSpacing(0);
			layoutEntityFIgureName0.setVertical(true);

			entityFIgureName0.setLayoutManager(layoutEntityFIgureName0);

			RectangleFigure nameArea1 = new RectangleFigure();

			nameArea1.setFill(false);
			nameArea1.setOutline(false);

			entityFIgureName0.add(nameArea1);

			GridLayout layoutNameArea1 = new GridLayout();
			layoutNameArea1.numColumns = 1;
			layoutNameArea1.makeColumnsEqualWidth = true;
			nameArea1.setLayoutManager(layoutNameArea1);

			fEntityFigureName = new WrappingLabel();

			fEntityFigureName.setText("entity");

			fEntityFigureName.setFont(FENTITYFIGURENAME_FONT);

			GridData constraintFEntityFigureName = new GridData();
			constraintFEntityFigureName.verticalAlignment = GridData.CENTER;
			constraintFEntityFigureName.horizontalAlignment = GridData.CENTER;
			constraintFEntityFigureName.horizontalIndent = 0;
			constraintFEntityFigureName.horizontalSpan = 1;
			constraintFEntityFigureName.verticalSpan = 1;
			constraintFEntityFigureName.grabExcessHorizontalSpace = true;
			constraintFEntityFigureName.grabExcessVerticalSpace = true;
			nameArea1.add(fEntityFigureName, constraintFEntityFigureName);

			RectangleFigure stereotypeArea1 = new RectangleFigure();

			entityFIgureName0.add(stereotypeArea1);

			fEntityFigureStereotype = new WrappingLabel();

			fEntityFigureStereotype.setText("stereotype");

			stereotypeArea1.add(fEntityFigureStereotype);

		}

		/**
		 * @generated
		 */
		public WrappingLabel getEntityFigureName() {
			return fEntityFigureName;
		}

		/**
		 * @generated
		 */
		public WrappingLabel getEntityFigureStereotype() {
			return fEntityFigureStereotype;
		}

		/**
		 * @generated
		 */
		public WrappingLabel getEntityAttribute() {
			return fEntityAttribute;
		}

	}

	/**
	 * @generated
	 */
	static final Font FENTITYFIGURENAME_FONT = new Font(Display.getCurrent(),
			Display.getDefault().getSystemFont().getFontData()[0].getName(),
			11, SWT.NORMAL);

}
